<!--
  新建分账用户

  @author terrfly
  @site https://www.jeequan.com
  @date 2022/05/09 14:20
-->
<template>
  <div>
    <a-drawer
      v-model:visible="vdata.visible"
      :closable="true"
      :maskClosable="false"
      width="80%"
      title="绑定分账接收者账号"
      @close="onClose"
    >
      <a-form layout="vertical">
        <a-row :gutter="40">
          <a-col :span="6">
            <a-form-item label="商户号">
              <div class="mch">
                <div class="cont">
                  <span v-if="!vdata.selectedMchAndIfcodeInfo.mchNo" style="color: #bfbfbf;">商户号</span>
                  {{ vdata.selectedMchAndIfcodeInfo.mchNo }}
                </div>
                <div class="search" @click="jeepayModelMchListRef.show()">
                  <search-outlined />
                </div>
              </div>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="选择商户应用">
              <a-select v-model:value="vdata.selectedMchAndIfcodeInfo.appId" placeholder="应用ID" @change="mchAppChangeFunc($event)">
                <a-select-option v-for="(item) in vdata.allMchAppList" :key="item.appId" :value="item.appId">{{ item.appName }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="选择要加入到的账号分组">
              <div style="display: flex;">
                <a-select v-model:value="vdata.selectedMchAndIfcodeInfo.receiverGroupId" placeholder="分账账号组">
                  <a-select-option v-for="(item) in vdata.allReceiverGroup" :key="item.receiverGroupId" :value="item.receiverGroupId">{{ item.receiverGroupName }}</a-select-option>
                </a-select>
                <a-button type="primary" style="margin-left:20px;" @click="groupInfoAddOrEditRef.show(vdata.selectedMchAndIfcodeInfo.mchNo)"><plus-outlined />新建</a-button>
              </div>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <a-divider style="margin-top: 0;margin-bottom:20px" />
      <div v-if="vdata.selectedMchAndIfcodeInfo.appId">  
        <a-form layout="vertical">
          <a-form-item label="选择接口">
            <a-select v-model:value="vdata.selectedMchAndIfcodeInfo.ifCode" style="width: 210px" placeholder="账号所属接口" @change="ifCodeChangeFunc">
              <a-select-option v-for="(item) in vdata.appSupportIfCodes" :key="item.ifCode" :value="item.ifCode">
                <div>
                  <span class="icon-style" :style="{backgroundColor: item.bgColor}">
                    <img class="icon" :src="item.icon">
                  </span>
                  {{ item.ifName }}
                </div>
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-form>
      </div>
      <JeepayModelMchList ref="jeepayModelMchListRef" showType="MCH" :mchNoAndName="true" @selectFinishFunc="selectFinishFunc" />


      <!-- 引入具体的接口组件  -->
      <JeepayDivisionReceiver ref="ifCodeComponentRef" />

      <div v-if="vdata.selectedMchAndIfcodeInfo.ifCode" class="btn">
        <a-button :loading="vdata.confirmBtnLoading" type="primary" style="margin-right: 10px" @click="reqBatchBindReceiver(0)"><check-outlined />确认绑定</a-button>
      </div>
    </a-drawer>

    <!-- 新增 / 修改 页面组件  -->
    <GroupInfoAddOrEdit ref="groupInfoAddOrEditRef" :callbackFunc="reloadGroup" />
  </div>
</template>

<script lang="ts" setup>

import GroupInfoAddOrEdit from '../group/AddOrEdit.vue'
import { reactive, ref,getCurrentInstance, provide, computed, nextTick } from 'vue'
import { API_URL_DIVISION_RECEIVER, API_URL_DIVISION_RECEIVER_GROUP, API_URL_MCH_APP, req, $getIfCodeByAppId } from '@/api/manage'
const { $infoBox } = getCurrentInstance()!.appContext.config.globalProperties

const jeepayModelMchListRef = ref()
const ifCodeComponentRef = ref()
const groupInfoAddOrEditRef = ref()

// 响应式数据
const vdata : any = reactive({
  visible: false, // 是否显示抽屉

  allMchAppList: [], // 所有的应用
  allReceiverGroup: [], // 所有的分账组
  appSupportIfCodes: [], // 商户应用支持的所有的支付接口

  selectedMchAndIfcodeInfo: {}, //选择的商户or渠道信息


  confirmBtnLoading: false,

})

// 向子组件注入： 当前选择的数据对象信息（包含 ifCode, mchNo, appId 等参数 ）
provide('selectedMchAndIfcodeInfo', computed( ()=> vdata.selectedMchAndIfcodeInfo) )


// 弹层打开事件
function show () {

  // 数据重置 
  vdata.allMchAppList = []
  vdata.allReceiverGroup = []
  vdata.appSupportIfCodes = []
  vdata.selectedMchAndIfcodeInfo = { }

  // 清空组件
  if(ifCodeComponentRef.value){
    ifCodeComponentRef.value.ifCodeChangeFunc()
  }

  vdata.visible = true // 显示弹层
}
// 抽屉关闭
function onClose () {
  vdata.visible = false
}

// 当选择的 app发生变化时
function mchAppChangeFunc(appId){

    vdata.selectedMchAndIfcodeInfo.ifCode = null //选择的接口置空

    // 清空组件
    if(ifCodeComponentRef.value){
      ifCodeComponentRef.value.ifCodeChangeFunc()
    }

    // 请求商户应用 支持的所有的支付接口
    $getIfCodeByAppId(appId).then((res) => {
        vdata.appSupportIfCodes = res
    })

}

// 选择商户/应用 完成后的 事件 
function selectFinishFunc(selectArray){

  if(!selectArray[0]){
    return $infoBox.message.error('选择信息不完整！')
  }

  vdata.selectedMchAndIfcodeInfo.mchNo = selectArray[0]

  jeepayModelMchListRef.value.close()

  reloadGroup() // 重新加载分组信息

  // 当商户选择完成后：  请求接口，获取所有应用，只有此处进行pageSize=-1传参
  vdata.selectedMchAndIfcodeInfo.appId = null
  vdata.selectedMchAndIfcodeInfo.ifCode = null
  req.list(API_URL_MCH_APP, { pageSize: -1, mchNo: vdata.selectedMchAndIfcodeInfo.mchNo }).then(res => {
    vdata.allMchAppList = res.records
    if (vdata.allMchAppList && vdata.allMchAppList.length > 0) { // 默认选中第一个 & 更新列表
      vdata.selectedMchAndIfcodeInfo.appId = vdata.allMchAppList[0].appId
    }

    // 存在appId 请求接口列表
    if(vdata.selectedMchAndIfcodeInfo.appId){
      mchAppChangeFunc(vdata.selectedMchAndIfcodeInfo.appId)
    }
  })
 
}


// 重新加载账号分组
function reloadGroup(){

    // 当商户选择完成后：  请求接口，获取所有分组信息，只有此处进行pageSize=-1传参
  vdata.selectedMchAndIfcodeInfo.receiverGroupId = null
  req.list(API_URL_DIVISION_RECEIVER_GROUP, { pageSize: -1, mchNo: vdata.selectedMchAndIfcodeInfo.mchNo }).then(res => {
    vdata.allReceiverGroup = res.records
    if (vdata.allReceiverGroup && vdata.allReceiverGroup.length > 0) { // 默认选中第一个 & 更新列表
      vdata.selectedMchAndIfcodeInfo.receiverGroupId = vdata.allReceiverGroup[0].receiverGroupId
    }
  })

}

// 选择支付接口 切换事件
function ifCodeChangeFunc(selectIfCode){

  ifCodeComponentRef.value.ifCodeChangeFunc(selectIfCode)
}

// 单条绑定 返回是否成功
function reqBatchBindReceiver (i) {

  // 获取参数（ 返回 Promise ）
  ifCodeComponentRef.value.getReqDataList().then(reqListRef => {

    if (reqListRef.length <= 0) {
      return $infoBox.message.error('请先添加账号')
    }

    // 完成了所有的绑定操作
    if (i >= reqListRef.length) {
      return $infoBox.message.success('已完成所有账号的绑定操作')
    }

    // 深度拷贝， 避免更改组件内的值
    let reqList = JSON.parse(JSON.stringify(reqListRef))

    // 当前的账号
    const currentReceiver = reqList[i]

    // 设置分组ID 和 其他信息
    currentReceiver.receiverGroupId = vdata.selectedMchAndIfcodeInfo.receiverGroupId
    currentReceiver.mchNo = vdata.selectedMchAndIfcodeInfo.mchNo
    currentReceiver.appId = vdata.selectedMchAndIfcodeInfo.appId
    currentReceiver.ifCode = vdata.selectedMchAndIfcodeInfo.ifCode

    if (currentReceiver.reqBindState === 1) { // 已经绑定成功， 不在重复发起
      return reqBatchBindReceiver(++i) // 递归继续绑定
    }

    if (!currentReceiver.accNo) {
      return $infoBox.message.error(`第${i + 1 }条： 接收方账号不能为空`)
    }

    if (currentReceiver.relationType === 'CUSTOM' && !currentReceiver.relationTypeName) {
      return $infoBox.message.error(`第${i + 1 }条： 自定义类型时接收方账号名称不能为空`)
    }

    if (!currentReceiver.divisionProfit || currentReceiver.divisionProfit <= 0 || currentReceiver.divisionProfit > 100) {
      return $infoBox.message.error(`第${i + 1 }条： 默认分账比例请设置在[0.01% ~ 100% ] 之间`)
    }

    vdata.confirmBtnLoading = true
    req.add(API_URL_DIVISION_RECEIVER, currentReceiver).then(apiRes => {
      // 绑定成功
      if (apiRes.bindState === 1) {

        ifCodeComponentRef.value.changeState(i, 1) // 状态变更
        reqBatchBindReceiver(++i) // 递归继续绑定

      } else {
        ifCodeComponentRef.value.changeState(i, 2) // 状态变更
        $infoBox.modalError(`第${i + 1 }条： 绑定异常`, `错误码:${apiRes.errCode || '未知'} , 错误信息:${apiRes.errMsg}`)
      }
    }).catch(() => {
      ifCodeComponentRef.value.changeState(i, 2) // 状态变更
    }).finally(() => {
      vdata.confirmBtnLoading = false
    })

  })
}

defineExpose({show})

</script>
<style scoped lang="less">
.btn{
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 70px;
}
.icon-style{
 
  /* background-color: black; */
  border-radius: 5px;
  padding-left: 2px;
  padding-right: 2px;
}
.icon{
  width: 15px;
  height: 14px;
  margin-bottom: 3px;
}
.text{
  margin-bottom: 10px;
}
.mch{
  box-sizing: border-box;
  height: 34px;
  padding: 0 11px 0 11px;
  color: rgba(0, 0, 0, 0.65);
  font-size: 14px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  .cont{
    width: 80%;
    height: 100%;
    //background-color: aqua;
    display: flex;
    //justify-content: center;
    align-items: center;
  }
  .search{
    width: 10%;
    height: 100%;
   // background-color: antiquewhite;
    display: flex;
    align-items: center;
    justify-content: center;
    
  }

}
</style>